import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:mobile_scanner/mobile_scanner.dart';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:scan_qr_codes/getGiteeservice.dart';
import 'package:url_launcher/url_launcher.dart';

import 'WeChatRobot.dart';
import 'package:logging/logging.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '二维码扫描',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const QRScannerPage(),
    );
  }
}

class QRScannerPage extends StatefulWidget {
  const QRScannerPage({super.key});

  @override
  State<QRScannerPage> createState() => _QRScannerPageState();
}

class _QRScannerPageState extends State<QRScannerPage> {
  final MobileScannerController cameraController = MobileScannerController();
  String scannedData = '';
  bool isScanning = false;
  bool isTorchOn = false;
  bool isFrontCamera = false;
  bool showScanner = false;
  String? wechatkey = '';
  bool wechatenabled = false;
  final Logger logger = Logger('QRScannerPage');
  //初始化时执行事件
  @override
  void initState() {
    super.initState();
    Logger.root.level = Level.ALL;
    Logger.root.onRecord.listen((record) {
      print('${record.level.name}: ${record.time}: ${record.message}');
    });
    //
    _checkNetwork()
        .then((hasNetwork) async {
          if (!hasNetwork) {
            bool? goSetting = await _showNoNetworkDialog();
            // 取消则不扫描，去设置则不扫描并引导用户
            if (goSetting == false) {
              //退出软件
              SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            } else {
              //引导用户打开网络设置
              await _openWifiSettings();
              SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            }
            return;
          }
        })
        .catchError((e) {
          logger.warning('网络检查失败: $e');
        });

    GiteeService giteeService = GiteeService();
    giteeService
        .getConfigurationJson()
        .then((config) {
          if (config != null) {
            //读取配置文件
            final description = config?["二维码"]["description"] as String?;
            final pattern =
                config?["二维码"]["app"]["pattern"]
                    as int?; //模式 pattern 表示模式 0是授权模式（使用过期日期控制），1是开关模式（直接使用enable控制开关）
            final enable =
                config?["二维码"]["app"]["enable"] as bool?; //开关 enable 表示是否启用
            final ending_date =
                config?["二维码"]["app"]["ending_date"]
                    as String?; //过期日期 ending_date 表示授权模式的过期日期
            final ending_datetime =
                config?["二维码"]["app"]["ending_datetime"]
                    as String?; //过期时间 ending_datetime 表示授权模式的过期时间
            wechatkey =
                config?["二维码"]["wechat"]["robot"]["key"]
                    as String?; //过期时间 ending_datetime 表示授权模式的过期时间

            wechatenabled =
                config?["二维码"]["wechat"]["robot"]["enabled"]
                    as bool; //过期时间 ending_datetime 表示授权模式的过期时间
            _check_enable(pattern, enable, ending_date, ending_datetime);

            logger.info(
              '配置文件加载成功: $description, 模式: $pattern, 开关状态: $enable, 过期日期: $ending_date, 过期时间: $ending_datetime , wechatkey: $wechatkey, wechatenabled: $wechatenabled',
            );
          }
        })
        .catchError((e) {
          logger.warning('GiteeService 初始化失败: $e');
        });
  }

  //判断权限，是否可以使用
  void _check_enable(
    final pattern,
    final enable,
    final ending_date,
    final ending_datetime,
  ) {
    if (pattern == 0) {
      //授权模式
      if (enable == true) {
        //开启
        if (ending_date != null && ending_datetime != null) {
          //有过期时间
          DateTime now = DateTime.now();
          DateTime endDate = DateTime.parse('$ending_date $ending_datetime');
          if (now.isBefore(endDate)) {
            logger.info('授权模式已启用，当前时间在过期时间之前');
          } else {
            //过期了
            _showerroDialog();
            logger.warning('授权模式已过期，请联系管理员');
          }
        } else {
          //没有过期时间
          _showerroDialog();
          logger.warning('授权模式开启，但没有设置过期时间，请联系管理员');
        }
      } else {
        //未开启
        _showerroDialog();
        logger.warning('授权模式未启用，请联系管理员');
      }
    } else if (pattern == 1) {
      //开关模式
      if (enable == true) {
        logger.info('开关模式已启用');
      } else {
        //退出程序
        _showerroDialog();
        logger.warning('开关模式未启用，请联系管理员');
      }
    } else {
      logger.warning('未知的模式: $pattern，请联系管理员');
    }
  }

  // 检查网络连接
  Future<bool> _checkNetwork() async {
    var connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult == ConnectivityResult.none) {
      return false;
    }
    // 进一步检测是否真的能联网
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  Future<void> _openWifiSettings() async {
    try {
      if (Platform.isAndroid) {
        final AndroidIntent intent = AndroidIntent(
          action: 'android.settings.WIFI_SETTINGS',
        );
        await intent.launch();
      } else if (Platform.isIOS) {
        // iOS 尝试两种方式
        final wifiUrl = Uri.parse('App-Prefs:root=WIFI');
        final settingsUrl = Uri.parse('App-Prefs:');

        if (await canLaunchUrl(wifiUrl)) {
          await launchUrl(wifiUrl, mode: LaunchMode.externalApplication);
        } else if (await canLaunchUrl(settingsUrl)) {
          await launchUrl(settingsUrl, mode: LaunchMode.externalApplication);
        } else {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('无法打开 WiFi 设置')));
        }
      }
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('错误: $e')));
    }
  }

  // 弹出美观的错误提示框
  Future<bool?> _showerroDialog() async {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false, // 必须点击按钮才能关闭
      builder: (context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.0), // 圆角边框
          ),
          elevation: 8, // 阴影效果
          icon: const Icon(
            Icons.error_outline,
            color: Colors.red,
            size: 48, // 更大的图标
          ),
          title: const Text(
            '程序无法使用',
            style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
            textAlign: TextAlign.center,
          ),
          content: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Divider(height: 1, thickness: 1), // 分隔线
              SizedBox(height: 16),
              Text(
                '当前程序运行异常，无法使用。\n请联系技术支持：胡鑫',
                style: TextStyle(fontSize: 16),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 8),
              Text(
                '电话: XXX-XXXX-XXXX',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ],
          ),
          actionsAlignment: MainAxisAlignment.center,
          actions: [
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red, // 红色按钮
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(120, 40), // 按钮大小
              ),
              onPressed: () async {
                Navigator.of(context).pop(true);
                if (Platform.isAndroid) {
                  SystemNavigator.pop(); // 退出应用
                } else {
                  // iOS/其他平台提示
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('请手动退出应用'),
                      duration: Duration(seconds: 2),
                    ),
                  );
                }
              },
              child: const Text('确认退出', style: TextStyle(fontSize: 16)),
            ),
          ],
        );
      },
    );
  }

  // 弹出无网络提示框
  Future<bool?> _showNoNetworkDialog() async {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AlertDialog(
          title: const Text('网络未连接'),
          content: const Text('当前未检测到网络连接，无法进行二维码扫描。请连接网络后重试。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(false);
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop(true);
                // 引导用户打开网络设置
                //await _openWifiSettings(); // 使用上面的方法
              },
              child: const Text('去设置'),
            ),
          ],
        );
      },
    );
  }

  @override
  void dispose() {
    cameraController.dispose();
    super.dispose();
  }

  // 解析扫描数据的方法
  String _extractBindingCode(String rawData) {
    try {
      // 如果是URL格式，提取最后的路径部分
      if (rawData.startsWith('http')) {
        Uri uri = Uri.parse(rawData);
        String path = uri.path;
        // 获取路径中最后一个斜杠后的内容
        if (path.isNotEmpty) {
          List<String> pathSegments = path.split('/');
          // 返回最后一个非空段
          for (int i = pathSegments.length - 1; i >= 0; i--) {
            if (pathSegments[i].isNotEmpty) {
              return pathSegments[i];
            }
          }
        }
      }
      // 如果不是URL或解析失败，返回原始数据
      return rawData;
    } catch (e) {
      // 解析出错时返回原始数据
      Logger.root.warning('数据解析失败: $e, 原始数据: $rawData');
      return rawData;
    }
  }

  // 新增发送绑定号的方法
  Future<void> _sendBindingCode() async {
    if (wechatkey == null || wechatkey!.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('企业微信机器人未配置或未启用'),
          duration: Duration(seconds: 2),
        ),
      );
      return;
    }
    if (wechatenabled == false) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('企业微信机器人未启用'),
          duration: Duration(seconds: 2),
          backgroundColor: Colors.redAccent,
        ),
      );
      return;
    }

    if (scannedData.isNotEmpty) {
      Logger.root.info('准备发送绑定号: $scannedData');
      var d = _extractBindingCode(scannedData);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('正在发送绑定号: $d'), duration: Duration(seconds: 2)),
      );
      WeChatRobot robot = WeChatRobot(wechatkey!);
      bool result = await robot.sendTextMessage(d);
      if (result) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('发送成功'), duration: Duration(seconds: 2)),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('发送失败'),
            backgroundColor: Colors.red,
            duration: Duration(seconds: 2),
          ),
        );
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('没有可发送的扫描数据'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  // 新增复制内容到剪贴板的方法
  void _copyToClipboard() {
    if (scannedData.isNotEmpty) {
      Clipboard.setData(ClipboardData(text: scannedData));
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('内容已复制到剪贴板'),
          duration: Duration(seconds: 1),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('二维码解析器'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions:
            showScanner
                ? [
                  IconButton(
                    icon: Icon(
                      isTorchOn ? Icons.flash_on : Icons.flash_off,
                      color: isTorchOn ? Colors.yellow : Colors.grey,
                    ),
                    onPressed: () {
                      setState(() {
                        isTorchOn = !isTorchOn;
                      });
                      cameraController.toggleTorch();
                    },
                  ),
                  IconButton(
                    icon: Icon(
                      isFrontCamera ? Icons.camera_front : Icons.camera_rear,
                    ),
                    onPressed: () {
                      setState(() {
                        isFrontCamera = !isFrontCamera;
                      });
                      cameraController.switchCamera();
                    },
                  ),
                ]
                : [],
      ),
      body: Column(
        children: [
          Expanded(
            flex: 4,
            child:
                showScanner
                    ? Stack(
                      children: [
                        MobileScanner(
                          controller: cameraController,
                          onDetect: (capture) {
                            final List<Barcode> barcodes = capture.barcodes;
                            for (final barcode in barcodes) {
                              if (barcode.rawValue != null) {
                                setState(() {
                                  scannedData = barcode.rawValue!;
                                  isScanning = false;
                                });
                                cameraController.stop();

                                // 自动复制解析后的数据到剪贴板
                                String extractedData = _extractBindingCode(
                                  scannedData,
                                );
                                Clipboard.setData(
                                  ClipboardData(text: extractedData),
                                );
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: Text('已复制到剪贴板: $extractedData'),
                                    duration: Duration(seconds: 2),
                                  ),
                                );
                              }
                            }
                          },
                        ),

                        // 只在扫描过程中显示扫描框
                        if (isScanning)
                          Center(
                            child: Container(
                              width: 250,
                              height: 250,
                              decoration: BoxDecoration(
                                border: Border.all(
                                  color: Colors.white,
                                  width: 2,
                                ),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Stack(
                                children: [
                                  // 四个角的标记线
                                  Positioned(
                                    top: 0,
                                    left: 0,
                                    child: _cornerLine(
                                      horizontal: false,
                                      left: true,
                                    ),
                                  ),
                                  Positioned(
                                    top: 0,
                                    right: 0,
                                    child: _cornerLine(
                                      horizontal: false,
                                      left: false,
                                    ),
                                  ),
                                  Positioned(
                                    bottom: 0,
                                    left: 0,
                                    child: _cornerLine(
                                      horizontal: true,
                                      left: true,
                                    ),
                                  ),
                                  Positioned(
                                    bottom: 0,
                                    right: 0,
                                    child: _cornerLine(
                                      horizontal: true,
                                      left: false,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        if (!isScanning && scannedData.isNotEmpty)
                          Center(
                            child: Container(
                              padding: const EdgeInsets.all(16),
                              color: Colors.black54,
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  const Text(
                                    '扫描完成！',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 24,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  Text(
                                    _extractBindingCode(scannedData),
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 16,
                                    ),
                                    textAlign: TextAlign.center,
                                  ),
                                ],
                              ),
                            ),
                          ),
                      ],
                    )
                    : Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(
                            Icons.qr_code_scanner,
                            size: 100,
                            color: Colors.grey,
                          ),
                          const SizedBox(height: 20),
                          const Text(
                            '点击开始即可扫描二维码',
                            style: TextStyle(fontSize: 18),
                          ),
                        ],
                      ),
                    ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text(
                    '扫描到的内容:',
                    style: Theme.of(context).textTheme.titleLarge,
                  ),
                  const SizedBox(height: 8),
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        children: [
                          Expanded(
                            child: SingleChildScrollView(
                              child: _buildSelectableText(),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () async {
                            bool hasNetwork = await _checkNetwork();
                            if (!hasNetwork) {
                              bool? goSetting = await _showNoNetworkDialog();
                              // 取消则不扫描，去设置则不扫描并引导用户
                              if (goSetting == false) {
                                //退出软件
                                SystemChannels.platform.invokeMethod(
                                  'SystemNavigator.pop',
                                );
                              } else {
                                //引导用户打开网络设置
                                await _openWifiSettings();
                                SystemChannels.platform.invokeMethod(
                                  'SystemNavigator.pop',
                                );
                              }
                              return;
                            }
                            setState(() {
                              if (!showScanner) {
                                showScanner = true;
                                isScanning = true;
                                scannedData = '等待扫描结果...';
                                cameraController.start();
                              } else {
                                isScanning = true;
                                scannedData = '等待扫描结果...';
                                cameraController.start();
                              }
                            });
                          },
                          child: Text(showScanner ? '再次扫描' : '开始扫描'),
                        ),
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: ElevatedButton(
                          onPressed:
                              (scannedData.isNotEmpty && !isScanning)
                                  ? _sendBindingCode
                                  : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green,
                          ),
                          child: const Text('发送绑定号'),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建可选择和长按复制的文本组件
  Widget _buildSelectableText() {
    if (scannedData.isEmpty) {
      return const SizedBox.shrink();
    }

    return SelectableText(
      scannedData,
      style: Theme.of(context).textTheme.bodyLarge,
      toolbarOptions: const ToolbarOptions(copy: true, selectAll: true),
      onTap: () {
        // 可选：添加点击事件处理
      },
    );
  }

  // 绘制扫描框的角标线
  Widget _cornerLine({required bool horizontal, required bool left}) {
    return Container(
      width: 25,
      height: 25,
      decoration: BoxDecoration(
        border: Border(
          top:
              horizontal
                  ? BorderSide(width: 3, color: Colors.blue)
                  : BorderSide.none,
          bottom:
              !horizontal
                  ? BorderSide(width: 3, color: Colors.blue)
                  : BorderSide.none,
          left:
              left ? BorderSide(width: 3, color: Colors.blue) : BorderSide.none,
          right:
              !left
                  ? BorderSide(width: 3, color: Colors.blue)
                  : BorderSide.none,
        ),
      ),
    );
  }
}
